<?php

namespace App\Library\Import;

use App\Library\Traits\ImportProductTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class ImportProduct implements ToCollection
{
    use ImportProductTrait;

    private Model $logic;

    public function __construct(Model $logic)
    {
        $this->logic = $logic;
    }

    /**
     * random
     * @param Collection $collection
     * @return void
     */
    public function collection(Collection $collection): void
    {
        $arr = [];
        foreach ($collection as $k => $v) {
            if ($k === 0) {
                if ($this->checkTitle($v)) return;
            } else {
                $name = htmlspecialchars(strip_tags(trim($v[0])));
                if (empty($name)) {
                    continue;
                } else if (strlen($name) > 255) {
                    $this->error('列:' . ('A' . $k + 2) . ' 长度不能超过255');
                    return;
                }
                $arr[] = [
                    'name' => $name,
                    'activityType' => $this->hActivityType($v[1]),
                    'activity' => $this->hActivity($v[2]),
                    'wildCare' => $this->hWildCare($v[3]),
                    'protect' => $this->hProtect($v[4]),
                    'stage' => $this->hStage($v[5]),
                    'label' => $this->hLabel($v[6]),
                    'gene' => $this->hGene($v[7]),
                    'content' => $this->hContent($v[8]),
                    'note' => $this->hNote($v[9]),
                    'psName' => $this->hPsName($v[10]),
                    'psPriceUnderlined' => $this->hPsPriceUnderlined($v[11]),
                    'psUsableStock' => $this->hPsUsableStock($v[12]),
                    'psBuyLimit' => $this->hPsBuyLimit($v[13]),
                ];
            }
        }
        if (empty($arr)) {
            $this->error('没有数据');
            return;
        }
        $this->logic->status = 1;
        $this->logic->extend = $arr;
        $this->logic->save();
    }
}
